#!/bin/bash 
NETWORK="192.168.4."
read -p "请输入创建虚拟机的数量:" CreateNum
echo  ${CreateNum}
  if [ "${CreateNum}" == "" ];then
      echo "虚拟机的数量 不能是空值"
      exit 1
#创建虚拟机数量太大就会再次确认
  elif [ ${CreateNum} -ge 3 ];then
      read -p  "需要创建虚拟机过大：${CreateNum} ,确定要创建么yes|no："  Confirm
      if [ "${Confirm}" == "no" ] || [ "${Confirm}" == "" ];then
             echo "确定创建${CreateNum} 台机器 请输入:yes, 程序退出！！！！！ "
             exit 1
      fi
                     
  else
      
      echo "虚拟机的数量是${CreateNum}"
  fi
read -p "请输入创建虚拟机起始ip:${NETWORK}" StartIP
  if [ "${StartIP}" == "" ];then
      echo "虚拟机起始ip值 不能是空值"
      exit 1
  else
     export Endip="`expr  $StartIP + $CreateNum - 1`"
     echo "创建虚拟机地址池:${NETWORK}${StartIP}-${NETWORK}${Endip}"
     echo "开始检测 网络地址可用性。。。。。。" 
  fi

#判断是否被占用
Rangeip=${StartIP}
#Endip="`expr  $Rangeip + $CreateNum`"
while [ $Rangeip -le $Endip ]; do
#	 echo "${NETWORK}${Rangeip}"
         ping -q -i 0.01 -c 3 ${NETWORK}${Rangeip}  &> /dev/null && echo ${NETWORK}${Rangeip} is alive
           if [ "$?" = "0"  ];then
              echo "${NETWORK}${Rangeip} is already used ，please check  network address range"
              exit 1 
           fi
	 let Rangeip+=1
done









read -p "请输入创建虚拟机主机名(必须是英文不能是中文):" VsHost
  if [ "${VsHost}" == "" ];then
      echo "虚拟机主机名 不能是空值"
      exit 1
  else
    echo "主机名 是${VsHost}"
  fi
read -p "请输入创建虚拟机内存大小(k),默认是2048:" VsMem
  if [ "${VsMem}" == "" ];then
       VsMem=2048
  fi

read -p "请输入创建虚拟机CPU大小(逻辑线程数),默认是2:" VsCpu
  if [ "${VsCpu}" == "" ];then
       VsCpu=2
  fi

  echo '''
请输入创建虚拟机的宿主机地址,列表如下:
       192.168.4.9
       192.168.4.12
       192.168.4.13
       192.168.4.14
       192.168.4.15 '''
read -p "输入宿主机地址(默认192.168.4.9):" DeployHost
  if [ "${DeployHost}" == "" ];then
       DeployHost=192.168.4.9
  fi





#terraform 资源 参数替换
rm /terraform/vcenter/terraform.tfstate* -fr
cp -ar /terraform/vcenter/variables.tf.temp /terraform/vcenter/variables.tf
cp -ar /terraform/vcenter/main.tf.temp /terraform/vcenter/main.tf


sed  -i  "s/CreateNum/${CreateNum}/g"  /terraform/vcenter/variables.tf
sed  -i  "s/StartIP/${StartIP}/g"  /terraform/vcenter/main.tf
sed  -i  "s/VsHost/${VsHost}/g"  /terraform/vcenter/variables.tf
sed  -i  "s/VsMem/${VsMem}/g"  /terraform/vcenter/variables.tf
sed  -i  "s/VsCpu/${VsCpu}/g"  /terraform/vcenter/variables.tf
sed  -i  "s/NETWORK/${NETWORK}/g"  /terraform/vcenter/variables.tf
sed  -i  "s/DeployHost/${DeployHost}/g"  /terraform/vcenter/variables.tf
sed  -i  "s/DeployHost/${DeployHost}/g"  /terraform/vcenter/main.tf

#执行创建虚拟机
cd /terraform/vcenter/
echo "开始创建虚拟机 !!!!!"
sleep 3



#echo ${VsMem}  ${VsCpu}
terraform apply   -auto-approve 
